//========================================================================
//Copyright 2007-2010 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at 
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================

package com.dyuproject.kvstore;

import java.util.Random;

/**
 * Time-based key that mutates the last character of the key.
 * The initial value is 'a' ... 
 * If the timestamp is not unique (e.g another operation on 
 * a different thread creates the key at the same time, the last character can be 
 * mutated to 'b-z'. 
 *
 * @author David Yu
 * @created Feb 2, 2010
 */
public class TimeBasedKey extends Mutable<String>
{
    
    static final LocalRandom LOCAL_RANDOM = new LocalRandom();
    
    private char[] value = (System.currentTimeMillis() + "a").toCharArray();
    private final Random random;
    
    public TimeBasedKey()
    {
        this(LOCAL_RANDOM.get());
    }
    
    public TimeBasedKey(Random random)
    {
        this.random = random;
    }
    
    public String getValue()
    {
        return new String(value);
    }
    
    /**
     * This mutates the time-based key.  The arg {@code dummy} is ignored so pass in null.
     */
    public void setValue(String dummy)
    {
        value[value.length - 1] = (char)(98 + random.nextInt(24));
    }

    private static final class LocalRandom extends ThreadLocal<Random>
    {
        protected Random initialValue()
        {
            return new Random();
        }
    }

}
